package com.zhang.crm.manager;

import com.zhang.crm.constant.Constants;
import com.zhang.crm.pojo.TClue;
import com.zhang.crm.pojo.TCustomer;
import com.zhang.crm.pojo.req.ConvertClientReq;
import com.zhang.crm.service.ClueService;
import com.zhang.crm.service.CustomerService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class ConvertCustomerManager {

    @Resource
    private ClueService clueService;

    @Resource
    private CustomerService customerService;

    @Transactional(rollbackFor = Exception.class)
    public Boolean convertCustomerManager(ConvertClientReq convertClientReq){
        //TODO 验证是否已经转了客户

        //修改线索
        TClue tClue = new TClue();
        tClue.setId(convertClientReq.getClueId());
        tClue.setState(Constants.CLUE_TO_CUSTOMER);
        Integer result = clueService.update(tClue);
        if (result == 0) {
            throw new RuntimeException("更新失败，查无此人");
        }

        //添加客户
        TCustomer tCustomer = new TCustomer();
        tCustomer.setClueId(convertClientReq.getClueId());
        tCustomer.setProduct(convertClientReq.getIntentionProduct());
        tCustomer.setDescription(convertClientReq.getDescription());
        //格式化日期
        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date parse = simpleDateFormat.parse(convertClientReq.getNextContactTime());
            tCustomer.setNextContactTime(parse);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        int i = customerService.addCustomer(tCustomer);
        return i > 0 ? true : false;
    }
}
